package tungsten.base.event;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 事件的中央处理器
 * @author lv
 *
 */
public class EventBus
{
	private static ConcurrentHashMap<Integer, CopyOnWriteArrayList<IEventDispatcher>> events = new ConcurrentHashMap<>();
	public static final String EVENT_THREAD = "EVENT_THREAD";
	/**
	 * 添加事件侦听
	 * @param type
	 * @param dispatcher
	 */
	public static void addEventListener(int type,IEventDispatcher dispatcher)
	{
		CopyOnWriteArrayList<IEventDispatcher> list = events.get(type);
		
		if(list == null)
		{
			CopyOnWriteArrayList<IEventDispatcher> newList = new CopyOnWriteArrayList<IEventDispatcher>();
			
			list = events.putIfAbsent(type, newList);
			
			if(list == null)
			{
				list = newList;
			}
		}

		list.addIfAbsent(dispatcher);
	}
	/**
	 * 移除事件侦听
	 * @param type
	 * @param dispatcher
	 */
	public static void removeEventListener(int type,IEventDispatcher dispatcher)
	{
		CopyOnWriteArrayList<IEventDispatcher> list = events.get(type);
		
		if(list == null) return;
		
		list.remove(dispatcher);
	}
	
	/**
	 * 发送事件 
	 * @param event
	 */
	public static void dispatchEvent(Event event)
	{
		CopyOnWriteArrayList<IEventDispatcher> list = events.get(event.getType());
		
		if(list == null || list.size() == 0) return;
		
		for(IEventDispatcher dispatcher : list)
		{
			dispatcher.onEvent(event);
		}
	}
}
